package com.example.demo.config;

import cn.hutool.core.convert.Convert;
import com.example.demo.Util.JWTUtil;
import com.example.demo.Util.ThreadLocallUtil;
import com.example.demo.po.User;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Component
@Slf4j
@Validated
public class doyinInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String authorization = request.getHeader("Authorization");
        if (authorization == null){
            log.info("没有token");
            response.setStatus(401);
            response.getWriter().write("没有token");
            return false;
        }
        if (authorization != null ) {
            Claims claims = JWTUtil.parseJWT(authorization);
            if (claims == null){
                log.info("token错误");
                response.setStatus(401);
                response.getWriter().write("token解析失败，不是正确的token");
                return false;
            }
            Object userId1 = claims.get("userId");
            Long userId = Convert.toLong(userId1);
            User user = new User();
            user.setUserId(userId);
            ThreadLocallUtil.setUser(user);
        }
        return  true;
    }
    //拦截器最后执行,删除线程变量threadlocal,防止内存
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
        ThreadLocallUtil.remove();
    }
}
